var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require('express-session');

//中间件
const validate = require('./middleware/validate');
const messages = require('./middleware/messages')
const user = require('./middleware/user');
const page = require('./middleware/page');
//模型
const Entry = require('./models/entry');
//路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var entries = require('./routes/entries');
const register = require('./routes/register'); //用户注册
const login = require('./routes/login'); //用户登录
const api = require('./routes/api'); //RestAPI


var app = express();

// var bodyParser = require('body-parser'); // 引用
//This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, 
//  which will parse the bodies of all incoming requests. This is the simplest setup.
// parse application/x-www-form-urlencoded 只接收 encode过的body
// app.use(bodyParser.urlencoded({
//   extended: true
// }));
// // parse application/json
// app.use(bodyParser.json());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('json spaces', 2);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'secret',
  resave: false,
  saveUninitialized: true
}));
app.use('/api', api.auth); //restapi 路由
app.use(user) //用户数据加载中间件  加的位置有讲究
app.use(messages); //用户消息，显示在 views/messages.ejs

// app.use('/', indexRouter);
app.use('/users', usersRouter);
app.get('/post', entries.form);
app.post('/post',
  validate.required('entry[title]'), //后端验证
  validate.lengthAbove('entry[title]', 2),
  entries.submit);
app.get('/', entries.list);
app.get('/register', register.form);
app.post('/register', register.submit);
app.get('/login', login.form);
app.post('/login', login.submit);
app.get('/logout', login.logout);
app.get('/api/user/:id', api.user);
app.post('/api/entry', entries.submit);
app.get('/api/entries/:page?', page(Entry.count), api.entries);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;